package com.itheima.stock.helper;


import com.google.common.util.concurrent.RateLimiter;
import com.itheima.stock.enums.CodeEnum;
import com.itheima.stock.response.ResponseResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * LimiterAspect
 *
 * @author DanLi
 * @date 2025/7/14
 */
@SuppressWarnings("ALL")
@Aspect  // 切面
@Component // 组件
public class LimiterAspect {
    @Autowired
    public RateLimiter rateLimiter;

    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.itheima.stock.annotation.Limiter)")
    public void pt() {
    }
    /**
     * 环绕通知
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("pt()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        boolean flag = rateLimiter.tryAcquire();
        if (!flag) {
            return ResponseResult.error(CodeEnum.FREQUENT_VISITS);
        }
        return joinPoint.proceed();
    }
}
